<?php

namespace app\common\controller;

use app\interactive\model\User as UserModel;
use app\interactive\model\Token as TokenModel;
use think\Request;
use think\response\Json;

class Api
{
    protected $request;
    protected $user_id;
    private $token;
    private $meta = [];
    protected $data = [];
    private $without_action = ['login'];
    private $without_controller = ['User'];

    public function __construct(Request $request)
    {
        // 允许来自任何来源的跨域请求
        // header("Access-Control-Allow-Origin: *");

        // // 允许的请求方法
        // header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");

        // // 允许的请求头
        // header("Access-Control-Allow-Headers: Content-Type, Authorization");

        // // 如果是预检请求，直接返回
        // if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
        //     exit(0);
        // }
        $this->request = $request;
        $this->initialize();
    }

    protected function initialize()
    {
        defined('NOW_DATE') or define('NOW_DATE', date("Y-m-d", $this->request->time()));
        defined('NOW_TIME') or define('NOW_TIME', date("Y-m-d H:i:s", $this->request->time()));

        if ($this->request->isPost()) {
            $param = json_decode(file_get_contents('php://input'), true) ?? $this->request->request();
            $this->meta = $param['meta'] ?? [];
            $this->data = $param['data'] ?? [];
        } else {
            $this->data = $this->request->get();
        }

        $this->user_id = $this->meta['user_id'] ?? null;
        $this->token = $this->meta['token'] ?? null;

        if (
            !in_array($this->request->controller(), $this->without_controller) &&
            !in_array(strtolower($this->request->action()), $this->without_action) &&
            strtolower(app('http')->getName()) == 'interactive'
        ) {
            $this->checkUserAuthentication();
        }
    }

    protected function checkUserAuthentication()
    {
        $user = UserModel::where(['id' => $this->user_id, 'status' => 0])->find();
        if (empty($user)) {
            $this->api_echo(100, '用户不存在', null);
        }

        $directory = substr($this->request->controller(), 0, 5);
        $type = $directory == 'wxapi' ? 1 : 3;
        $token = TokenModel::where([
            'user_id' => $this->user_id,
            'token' => $this->token,
            'type' => $type
        ])->where('expire', '>', time())->find();

        if (empty($token)) {
            $this->api_echo(104, '身份验证有误', [$this->request->controller(), $this->request->action()]);
        }
    }

    public function get_meta()
    {
        return $this->meta;
    }

    public function get_data()
    {
        return $this->data;
    }

    public function get_param($key = '', $default = null)
    {
        return $this->data[$key] ?? $default;
    }

    public function api_echo($code=0, $msg='请求成功', $data=[], $exchange_null=true)
    {
        $meta = [
            'code'  =>  $code,
            'msg'   =>  $msg,
        ];

        $res = [
            'data'  =>  $data,
            'meta'  =>  $meta,
        ];

        if($exchange_null) {
            array_walk_recursive($res, function (&$item) {
                $item = null === $item ? '' : $item;
            });
        }

        $json_res = json_encode($res);

        echo $json_res;
        exit;
    }

    public function success($msg = '', $data = null, $code = 200): Json
    {
        return json(['msg' => $msg, 'code' => $code, 'data' => $data]);
    }

    public function error($msg = '', $code = 400): Json
    {
        return json(['msg' => $msg, 'code' => $code]);
    }
}
